package com.cn.sys.frame.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.cn.sys.common.Constants;
import com.cn.sys.frame.util.page.PageData;
import com.cn.sys.main.entity.SysFunction;
import com.cn.sys.main.entity.SysModule;
import com.cn.sys.main.entity.SysUser;

public class BaseController{

	/**
	 * HttpSession中获取用户信息
	 * @param request
	 * @return
	 */
    protected SysUser getSessionUser(HttpServletRequest request) {
        return (SysUser) request.getSession().getAttribute(Constants.USER_CONTEXT);
    }
    /**
     * 把用户信息保存到HttpSession中
     * @param request
     * @param user
     */
    protected void setSessionUser(HttpServletRequest request,SysUser user) {
    	//user.setPassWord("");
        request.getSession().setAttribute(Constants.USER_CONTEXT, user);
    }
    
    /**
     * 把用户的模块信息和功能信息保存到HttpSession中
     * @param request
     * @param list1
     * @param list2
     */
    protected void setSessionModuleAndFunc(HttpServletRequest request, List<SysModule> list1 , List<SysFunction> list2) {
        request.getSession().setAttribute(Constants.USER_MODULES, list1);
        request.getSession().setAttribute(Constants.USER_FUNCTIONS, list2);
    }
	
    /**
     * 获取easyui分页参数
     * @param request
     * @return
     */
	@SuppressWarnings("rawtypes")
	protected PageData createPageDataFromRequest(HttpServletRequest request){
		PageData pageData = new PageData();
		String rows = request.getParameter("rows");
		if(StringUtils.isNotBlank(rows) && StringUtils.isNumeric(rows)){
			int pageSize = Integer.valueOf(rows).intValue();
			pageData.setPageSize(pageSize);
		}else {
			pageData.setPageSize(Constants.DEFAULT_PAGE_SIZE);
		}
		String page = request.getParameter("page");
		if(StringUtils.isNotBlank(page) && StringUtils.isNumeric(page)){
			int pageNumber = Integer.valueOf(page).intValue();
			pageData.setPageNumber(pageNumber);
		}else {
			pageData.setPageNumber(1);
		}
		return pageData;
	}
	
	protected void getTextData (HttpServletResponse response, String str) {
		response.setContentType("text/html");
		response.setHeader("Cache-Control", "no-store"); //HTTP1.1
        response.setHeader("Pragma", "no-cache"); //HTTP1.0
        response.setDateHeader("Expires", 0); //prevents catching at proxy server
        PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(str);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				out.flush();
		        out.close();
			}
		}
	}
}
